package com.marcowu.study.spb.tracing.manager;

import com.marcowu.study.spb.tracing.zipkin.TracerBuiler;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.Tracer;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SampleManager {

  private static Logger s_logger = LoggerFactory.getLogger(SampleManager.class);

  private Tracer tracer = TracerBuiler.getZipkinTracer("sample1");

  @Autowired
  private OkHttpClient httpClient;

  public String sayBye() throws Exception {
    tracer.buildSpan("sayBye").asChildOf(tracer.activeSpan().context()).withTag("sayBye", "opentracing").start();
    return getHttp("zipkinTest/tracing/sayBye");
  }

  public String sayHello() throws Exception {
    Span span = tracer.buildSpan("sayHello").withTag("hello", "opentracing").start();
    try (Scope scope = tracer.scopeManager().activate(span)) {
      scope.close();
      return getHttp("zipkinTest/tracing/sayHello");
    }
  }

  public void bye() {
    Span span = tracer.buildSpan("bye").withTag("bye", "opentracing").start();
    try (Scope scope = tracer.scopeManager().activate(span)) {
      System.out.println("bye");
    }
  }

  public void hello() {
    Span parentSpan = tracer.scopeManager().activeSpan();
    Span span = tracer.buildSpan("hello").asChildOf(parentSpan.context()).start();
    if (span != null) {
      span.setTag("hello", "opentracing");
      span.log("hello");
    }
  }

  private String getHttp(String path) {
    try {
      HttpUrl url = new HttpUrl.Builder().scheme("http").host("localhost").port(9000).addPathSegments(path).build();
      Request.Builder requestBuilder = new Request.Builder().url(url);

      Request request = requestBuilder.build();
      Response response = httpClient.newCall(request).execute();
      if (response.code() >= 400) {
        throw new RuntimeException("Bad HTTP result: " + response);
      }
      return response.body().string();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

}
